import 'package:pizza_test/model/chefmodel.dart';
import 'package:sqflite/sqflite.dart';
class MySQLiteDB {
  
  Database db;

  Future open() async {
    var databasesPath = await getDatabasesPath();
    String path = databasesPath+"SQLDB_PATH.db";
    db = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      await db.execute('''
      create table pizza ( 
        pizzaId integer primary key autoincrement, 
        pizzaSize integer,
        chefId integer,
        toppings text)
      '''
      );
    });
  }

  Future insertList(List<Pizza> pizzas, int chefId) async {
    if(db == null) await open();
    pizzas.forEach((pizza){
       String topings = pizza.toppings.join(",");
       if(topings == null) topings = "";
       db.insert("pizza",
        {
          "pizzaId": pizza.pizzaId, 
          "pizzaSize": pizza.size.index, 
          "toppings": topings,
          "chefId": chefId
       }
      );
    });
  }

  Future delete(int id) async {
    if(db == null) await open();
    return await db.delete("pizza", where: 'pizzaId = ?', whereArgs: [id]);
  }

  Future<List<Pizza>> query() async {
    if(db == null) await open();
    List<Map<String, dynamic>> records = await db.query('pizza');
    List<Pizza> list = [];
    records.forEach((val){
      String toping = val["toppings"];
      list.add(Pizza(
        pizzaId: val["pizzaId"],
        size: EpizzaSize.values[val["pizzaSize"]], 
        toppings: toping.split(","),
        chefId: val["chefId"]
      ));
    });
    return list;
  }

  Future close() async {
    if(db == null) await open();
    db.close();
  }
}